package com.sky.service.impl;


import cn.mybatis.mp.core.sql.executor.chain.QueryChain;
import com.sky.dto.SaveScriptPlayerCountsListDTO;
import com.sky.entity.ScriptPlayerCounts;
import com.sky.mapper.ScriptPlayerCountsMapper;
import com.sky.service.ScriptPlayerCountsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author majun
 * @package com.sky.service.impl
 * @date 2025/6/21 13:57
 */
@Service
public class ScriptPlayerCountsServiceImpl implements ScriptPlayerCountsService {

    @Autowired
    private ScriptPlayerCountsMapper scriptPlayerCountsMapper;

    /**
     * 保存和修改剧本人数列表
     *
     * @param saveScriptPlayerCountsListDTO 保存和修改剧本人数列表DTO
     */
    public void saveScriptPlayerCountsList(SaveScriptPlayerCountsListDTO saveScriptPlayerCountsListDTO) {
        
        // 获取剧本ID
        Long scriptId = Long.valueOf(saveScriptPlayerCountsListDTO.getScriptId());
        
        // 先查询该剧本的所有现有人数记录
        List<ScriptPlayerCounts> existingCounts = QueryChain.of(scriptPlayerCountsMapper)
                .eq(ScriptPlayerCounts::getScriptId, scriptId)
                .list();
        
        // 删除现有记录
        for (ScriptPlayerCounts existingCount : existingCounts) {
            scriptPlayerCountsMapper.deleteById(existingCount.getId());
        }
        
        // 如果玩家数量数组不为空，则批量插入新记录
        if (saveScriptPlayerCountsListDTO.getPlayerCount() != null && saveScriptPlayerCountsListDTO.getPlayerCount().length > 0) {
            List<ScriptPlayerCounts> scriptPlayerCountsList = new ArrayList<>();
            
            for (String playerCountStr : saveScriptPlayerCountsListDTO.getPlayerCount()) {
                ScriptPlayerCounts scriptPlayerCounts = new ScriptPlayerCounts();
                scriptPlayerCounts.setScriptId(scriptId);
                scriptPlayerCounts.setPlayerCount(Integer.valueOf(playerCountStr));
                scriptPlayerCountsList.add(scriptPlayerCounts);
            }
            
            // 批量保存
            scriptPlayerCountsMapper.saveBatch(scriptPlayerCountsList);
        }
    }
    
}
